Angular Date Pipe & formatting dates in Angular with examples

您所在的位置:网站首页 angular11 foreach Angular Date Pipe & formatting dates in Angular with examples

Angular Date Pipe & formatting dates in Angular with examples

2024-01-27 21:05| 来源: 网络整理| 查看: 265

Angular date pipe used to format dates in angular according to the given date formats,timezone and country locale information.

Using date pipe, we can convert a date object, a number (milliseconds from UTC) or an ISO date strings according to given predefined angular date formats or custom angular date formats.

Table of ContentsHow to Use Angular Date Pipe

Angular date pipe accpets three parameters

FormatTimezoneLocale{{ date_Value | date [ : format [ : timezone [ : locale ] ] ] }} ParameterDescriptionformatWe can pass predefined angular date formats or our custom date format as a parameter. The default value is 'mediumDate' (Optional parameter)timezoneThe default timezone is local system timezone of the user's machine. To change the timezone we can pass timezone offset ('0530') or standard UTC/GMT (IST) or continental US timezone abbreviation and it is an optional parameterlocalerepresents locale format rules to use. Default value is our project locale (en_US) if set or undefined.Optional parameterAngular Date Pipe Examples

Now we will go through few angular date pipe examples to understand it further.

I have created a date pipe component in my Angular project and added current datetime values in different formats like milliseconds,date object,datetime string,ISO datetime string.

import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-datepipe', templateUrl: './datepipe.component.html', styleUrls: ['./datepipe.component.scss'] }) export class DatepipeComponent implements OnInit { todayNumber: number = Date.now(); todayDate : Date = new Date(); todayString : string = new Date().toDateString(); todayISOString : string = new Date().toISOString(); constructor() { } ngOnInit() { } }

Now in my component I am displaying them using angular date pipe as shown below.

DateTime as Milliseconds : {{todayNumber}} datepipe:{{todayNumber | date}}

DateTime as object : {{todayDate}} datepipe:{{todayDate | date}}

DateTime as string : {{todayString}} datepipe:{{todayString | date}}

DateTime as iso string : {{todayISOString}} datepipe:{{todayISOString | date}}

Output: DateTime as Milliseconds : 1560617468681 datepipe:Jun 15, 2019 DateTime as object : Sat Jun 15 2019 22:21:08 GMT+0530 (India Standard Time) datepipe:Jun 15, 2019 DateTime as string : Sat Jun 15 2019 datepipe:Jun 15, 2019 DateTime as iso string : 2019-06-15T16:51:08.681Z datepipe:Jun 15, 2019

All types of datetime values displays the date in ‘MMM d, y’ format which is default Angular date format ‘mediumDate’

To change the datetime format in angular we have to pass date time format parameter to the angular pipe as shown below

{{ date_value | date :'short'}} // 6/15/19, 5:24 PM

The format ‘short’ is one of the predefined date formats in angular which converts our date value to ’M/d/yy, h:mm a’ format.

List of all predefined date formats in AngularDate FormatAngular datepipe codeResultM/d/yy, h:mm a{{todayDate | date:'short'}}6/15/19, 10:54 PMMMM d, y, h:mm:ss a{{todayDate | date:'medium'}}Jun 15, 2019, 10:54:25 PMMMMM d, y, h:mm:ss a z{{todayDate | date:'long'}}June 15, 2019 at 10:54:25 PM GMT+5EEEE, MMMM d, y, h:mm:ss a zzzz{{todayDate | date:'full'}}Saturday, June 15, 2019 at 10:54:25 PM GMT+05:30M/d/yy{{todayDate | date:'shortDate'}}6/15/19MMM d, y{{todayDate | date:'mediumDate'}}Jun 15, 2019MMMM d, y{{todayDate | date:'longDate'}}June 15, 2019EEEE, MMMM d, y{{todayDate | date:'fullDate'}}Saturday, June 15, 2019h:mm a{{todayDate | date:'shortTime'}}10:54 PMh:mm:ss a{{todayDate | date:'mediumTime'}}10:54:25 PMh:mm:ss a z{{todayDate | date:'longTime'}}10:54:25 PM GMT+5h:mm:ss a zzzz{{todayDate | date:'fullTime'}}10:54:25 PM GMT+05:30

Angular date pipe has 12 predefined date formats as shown in above table.

We have to pass first parameter “format” as quoted string with the predefined date format names listed below.

shortmediumlongfullshortDatemediumDatelongDatefullDateshortTimemediumTimelongTimefullTimeAngular date pipe timezone example

In addition to the date format we can pass timezone as a parameter to date pipe to display date in particular timezone.

The timezone parameter can be timezone offset (‘0530’) or standard UTC/GMT (IST) or continental US timezone abbreviation.

For example to display to time in IST timezone

Today is {{todayDate | date:'short':'IST'}} Today is {{todayDate | date:'short':'+0530'}} Result: Today is 6/19/19, 12:29 PM How to display UTC date time in angular using date pipe

To display UTC date and time in Angular we have to pass timezone parameters as ‘UTC’ or timezone offset as ‘+0000’ as shown below

Today is {{todayDate | date:'short':'UTC'}} Today is {{todayDate | date:'short':'+0000'}} Result: Today is 6/19/19, 11:11 AM Angular date pipe example with country locale

To display date according to country locale format rules, We have to pass country locale code as a third parameter to angular date pipe as shown below.

For example France follows “Central European Summer Time” and it has a timezone offset ‘+0200’.

To display date time in french locale in Angular use locale code ‘fr’ as parameter as shown below

French date time is {{todayDate | date:'full':'+0200':'fr'}}

Result: French date time is mercredi 19 juin 2019 à 13:25:15 GMT+02:00

But the above code returns the error in console saying Missing locale data for the locale “fr”.

In our application we dont have locale information for ‘fr’

To add the country locale information refer Angular currency pipe article

Creating Custom Date Pipe in Angular

The default date format in Angular is ‘mediumDate’.

What if we want to change it and replace it with our own custom format like ‘EEEE d MMMM y h:mm a’

Which displays time as ‘Wednesday 19 June 2019 8:33 PM’.

In our angular projects, we will be displaying dates very frequently and each time we need to pass the format parameter.

To avoid this We can create our own custom date pipe with the above format, use it across the application as shown below.

{{ todayDate | customDate }} Result: Wednesday 19 June 2019 8:33 PM

To create a custom date pipe follow the below steps

Create a file named custom.datepipe.ts add the below code.

import { Pipe, PipeTransform } from '@angular/core'; import { DatePipe } from '@angular/common'; @Pipe({ name: 'customDate' }) export class CustomDatePipe extends DatePipe implements PipeTransform { transform(value: any, args?: any): any { return super.transform(value, "EEEE d MMMM y h:mm a"); } }

And import CustomDatePipe in app.module.ts and add it in declaration array of AppModule.

import {CustomDatePipe} from './custom.datepipe'; @NgModule({ declarations: [ CustomDatePipe ]);

Now we can use our custom date pipe in component file as shown below

{{todayDate | customDate}} Result: Thursday 20 June 2019 4:15 AM Defining Custom date formats in Angular

In addition to the above date time formats,we can define our own custom datetime formats using the below symbols.

For example {{today | date:'GGGG'}} displays the era of time “Anno Domini”

We can combine these symbols to display our own date formats as shown below.

{{today | date:'EEEE d MMMM y GGGG'}} // Tuesday 18 June 2019 Anno Domini Format NameFormat specifierEg. ResultEraG, GG & GGG(Abbreviated)ADGGGG(Wide)Anno DominiGGGGG(Narrow)AYeary(Numeric: minimum digits)2019yy(Numeric: 2 digits + zero padded)19yyy(Numeric: 3 digits + zero padded)2019yyyy(Numeric: 4 digits or more + zero padded)2019MonthM(Numeric: 1 digit)6MM(Numeric: 2 digits + zero padded)06MMM(Abbreviated)JunMMMM(Wide)JuneMMMMM(Narrow)JMonth standaloneL(Numeric: 1 digit)6LL(Numeric: 2 digits + zero padded)06LLL(Abbreviated)JunLLLL(Wide)JuneLLLLL(Narrow)JWeek of yearw(Numeric: minimum digits)25ww(Numeric: 2 digits + zero padded)25Week of monthW(Numeric: 1 digit)4Day of monthd(Numeric: minimum digits)16dd(Numeric: 2 digits + zero padded)16Week dayE, EE & EEE(Abbreviated)SunEEEE(Wide)SundayEEEEE(Narrow)SEEEEEE(Short)SuPerioda, aa & aaa(Abbreviated)PMaaaa(Wide)PMaaaaa(Narrow)pPeriod*B, BB & BBB AbbreviatedmidBBBB Wideam, pm, midnight, noon, morning, afternoon, evening, nightBBBBB NarrowmdPeriod standalone*b, bb & bbb Abbreviatedmidbbbb Wideam, pm, midnight, noon, morning, afternoon, evening, nightbbbbb NarrowmidHour 1-12h(Numeric: minimum digits)10hh(Numeric: 2 digits + zero padded)10Hour 0-23H(Numeric: minimum digits)22HH(Numeric: 2 digits + zero padded)22Minutem(Numeric: minimum digits)35mm(Numeric: 2 digits + zero padded)35Seconds(Numeric: minimum digits [0 to 59])28ss(Numeric: 2 digits + zero padded [00 to 59])28Fractional secondsS(Numeric: 1 digit [0 to 9])1SS(Numeric: 2 digits + zero padded [00 to 99])13SSS(Numeric: 3 digits + zero padded [000 to 9999 milliseconds])135Zonez, zz & zzz(Short specific non location format)GMT+5zzzz(Long specific non location format (fallback to OOOO))GMT+05:30Z, ZZ & ZZZ(ISO8601 basic format)+0530ZZZZ(Long localized GMT format)GMT+05:30ZZZZZ(ISO8601 extended format + Z indicator for offset 0 (= XXXXX))+05:30O, OO & OOO(Short localized GMT format)GMT+5OOOO(Long localized GMT format)GMT+05:30


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3